package com.mateng.treasurechest.model

import com.mateng.treasurechest.API_URL
import com.mateng.treasurechest.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ServiceGenerator {

    private val CONNECT_TIME_OUT = 15
    private val READ_TIME_OUT = 30
    private val WRITE_TIME_OUT = 30

    private fun buildOkHttpClient(): OkHttpClient {
        val httpClient = OkHttpClient.Builder()

        if (BuildConfig.DEBUG) {
            val logInterceptor = HttpLoggingInterceptor()
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
            httpClient.addInterceptor(logInterceptor)
        }
        //设置超时
        httpClient.connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)
        httpClient.readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)
        httpClient.writeTimeout(WRITE_TIME_OUT.toLong(), TimeUnit.SECONDS)

        //错误重连
        httpClient.retryOnConnectionFailure(true)
        return httpClient.build()
    }

    fun <T> createService(serviceClass: Class<T>, host: String = API_URL): T {
        val retrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(host)
                .client(buildOkHttpClient()).build()
        return retrofit.create(serviceClass)
    }

}
